// pages/danger/selfAdd/index.js
import Dialog from '../../../dist/dialog/dialog.js';
import Toast from '../../../dist/toast/toast.js';

var app = getApp()
var util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,


    inspectId: 0,
    inspectList: [],
    title: '检查表标题',
    checkNum: '',
    preCheckDate: new Date(),
    preCheckDateStr: '',
    head: ['序号', '检查项目', '检查内容', '操作'],
    hiddenModal: true,
    inspectPublicId: 0,
    processInstanceId: "",
    taskId: "",
    dangerLevelOptions: ['一般(C级)', '一般(B级)', '重大(A级)'],


    selectLevel: "一般（C级）",
    inspectListPublic: {},
    inspectListPublicIndex: 0, //当前编辑的检查项目在inspectList中的index
    deadline: "",
    inspectResult: "", //检查记录
    needChange: false,
    tempImagePaths: [],
    inspectImageIds: [],
    dangerListCount: 0,//统计当前隐患的个数
    companyName: '',
    deptName: '',
    companyId: 0,
    deptId: '',
    inspectType: 0,//检查的类型，0自查，1检查，2排查或督查
    taskDefineKey: 'usertask2'//检查表所处的状态  usertask2 -待检查 usertask4-发布整改单 usertask7-待整改 usertask9-待验收
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    this.setData({
      inspectId: options.inspectId,
      inspectType: options.inspectType,
      companyName: options.companyName,
      companyId: options.companyId,
      deptName: options.deptName,
      deptId: options.deptId
    })
    var inspect = options.inspect
    if (inspect == "true") {
      that.loadInspect(options.inspectId)
    } else {
      that.loadInspectPublicDetail(options.inspectId);
    }
  },
  /**
   * 加载隐患自查的模板表
   */
  loadInspect(inspectId) {
    var inspectDate = new Date()
    var header;
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };

    var that = this
    wx.request({
      header: header,
      method: 'POST',
      url: app.globalData.baseUrl + '/safe/danger/inspectList/find',
      data: {
        inspectId: inspectId,
        sortField: 'inspect_project',
        sortOrder: 'asc'
      },
      success(res) {
        var inspectList = res.data.data
        for (var i = 0; i < inspectList.length; i++) {
          inspectList[i].inspectResult = "合格"
          inspectList[i].needChange = 0
        }
        that.setData({
          inspectList: inspectList
        })
        var checkNum = '';
        if (that.data.inspectType == 0) {
          checkNum = "隐患自查小程序" + util.formatTime(new Date())
        } else if (that.data.inspectType == 1) {
          checkNum = "隐患检查小程序" + util.formatTime(new Date())
        } else {
          checkNum = "隐患排查小程序" + util.formatTime(new Date())
        }
        var params = {
          dangerInspectListPublicList: inspectList,
          checkNum: checkNum, //隐患检查编号
          inspectId: inspectId,
          leaderUser: "",
          leaderUserId: "",
          name: "隐患检查表小程序",
          predictInspectDate: inspectDate,
          publicCompanyId: app.globalData.user.companyId,
          publicDeptId: app.globalData.user.companyId,
          status: 0,
          targetDeptId: that.data.companyId,
          activitiParams: {
            applyUserId: 1,
            check: false,
            type: that.data.inspectType
          }
        }
        //获取检查表的名字
        wx.request({
          header: header,
          url: app.globalData.baseUrl + '/safe/danger/inspect/find',
          method: 'POST',
          data: {
            dangerInspect: {
              id: inspectId
            },
          },
          success(res) {
            that.setData({
              title: res.data.data.list[0].name
            })
            params.name = res.data.data.list[0].name + util.formatTime(new Date())
            // that.publicSelfInspect(params, header)
          }
        })
      }
    })

  },
  /**
   * 显示记录隐患的窗口
   */
  showInspectModal(e) {
    var index = e.currentTarget.dataset.index
    var inspectPublicListId = e.currentTarget.dataset.inpsectpubliclistid
    var inspectPublicList = this.data.inspectList[index]
    this.setData({
      hiddenModal: false,
    })
    this.setData({
      inspectListPublic: inspectPublicList,
      inspectListPublicIndex: index
    })
    this.initInspectListPublic(inspectPublicList)
  },
  /**
   * 点击记录，加载隐患记录的信息
   */
  initInspectListPublic(inspectPublicList) {
    var needChange = false;
    if (inspectPublicList.needChange == 0) {
      needChange = false
    } else {
      needChange = true
    }
    var deadline = ''
    if (inspectPublicList.deadline) {
      deadline = util.formatTime(new Date(inspectPublicList.deadline), 'Y/M/D')

    } else {
      deadline = util.formatTime(new Date())
    }
    this.setData({
      inspectResult: inspectPublicList.inspectResult,
      deadline: deadline,
      selectLevel: '一般(C级)',
      needChange: needChange,
      tempImagePaths: inspectPublicList.dangerPics
    })
    if (inspectPublicList.hiddenDangerLevel) {
      this.setData({
        selectLevel: inspectPublicList.hiddenDangerLevel,
      })
    }
  },
  /**
   * 将隐患检查记录的结果暂存到data中去
   */
  bindInspectResultBlur(e) {
    this.setData({
      inspectResult: e.detail.value
    })
  },
  /**
   * 隐藏窗口
   */
  hiddenInspectModal() {
    this.setData({
      hiddenModal: true
    })
  },
  
  /**
   * 保存单个隐患检查记录
   */
  saveInspectList() {
    var that = this
    var inspectNeedChange = 0;
    if (this.data.needChange) {
      inspectNeedChange = 1;
    }
    var header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    var params = {
      inspectResult: this.data.inspectResult,
      deadline: this.data.deadline,
      id: this.data.inspectListPublic.id,
      needChange: inspectNeedChange,
      hiddenDangerLevel: this.data.selectLevel
    }
    wx.showLoading({
      title: '保存中.....',
    })
    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/inspectListPublic/update',
      header: header,
      method: "POST",
      data: params,
      success(res) {
        if (res.data.success) {
          var param = "inspectList[" + that.data.inspectListPublicIndex + "]"
          var inspectListPublic = that.data.inspectList[that.data.inspectListPublicIndex]
          inspectListPublic.deadline = that.data.deadline
          inspectListPublic.needChange = that.data.needChange
          inspectListPublic.hiddenDangerLevel = that.data.selectLevel
          inspectListPublic.inspectResult = that.data.inspectResult
          inspectListPublic.deadlineStr = util.formatTime(new Date(that.data.deadline))
          var inspectList = that.data.inspectList
          inspectList[that.data.inspectListPublicIndex] = inspectListPublic
          that.countDanger()
          wx.hideLoading()
          that.setData({
            inspectList: inspectList,
            hiddenModal: true
          })
        }
      }
    })

  },

  /**
   * 统计当前隐患个个数
   */
  countDanger() {
    var inspectList = this.data.inspectList
    var count = 0;
    for (var i = 0; i < inspectList.length; i++) {
      if (inspectList[i].needChange == 1) {
        count = count + 1;
      }
    }
    this.setData({
      dangerListCount: count
    })
  },

 

  
  
  /**
   * 将加载的自查表发布
   */
  publicSelfInspect(params, header) {

    var that = this
    params.status = 2
    wx.request({
      header: header,
      url: app.globalData.baseUrl + '/safe/dangerFlow/startDangerFlow',
      method: 'POST',
      data: params,
      success(res) {

        if (res.data.success) {
          var inspectPublicId = res.data.data.businesskey
          that.setData({
            inspectPublicId: inspectPublicId
          })
          that.loadInspectPublicDetail(inspectPublicId)
          if (res.data.data.myTasks.length > 0) {
            that.setData({
              taskId: res.data.data.myTasks[0].id
            })
          }
        }
      }
    })
  },
  /**
   * 保存检查时间
   */
  saveInspectDate() {
    var header;
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    var that = this
    var params = {
      inspectDate: new Date(),
      id: that.data.inspectPublicId
    }
    wx.request({
      header: header,
      url: app.globalData.baseUrl + '/safe/danger/inspectPublic/update',
      method: 'POST',
      data: params,
      success(res) {
        //保存返回到待检查列表去
        wx.redirect({
          url: '/pages/danger/dangerTaskList/dangerTaskList?taskDefineKey=usertask2'
        })
      }
    })
  },
  /**
   * 加载发布的隐患排查的检查单
   */
  loadInspectPublicDetail(inspectPublicId) {

    var that = this
    var header;
    that.setData({
      inspectPublicId: inspectPublicId
    })
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/inspectPublic/detail',
      header: header,
      method: "POST",
      data: {
        id: inspectPublicId
      },
      success(res) {
        var inspectList = res.data.data.dangerInspectListPublicList
        that.setData({
          inspectType: res.data.data.type,
          checkNum: res.data.data.checkNum,
        })
        for (var i = 0; i < inspectList.length; i++) {
          if (inspectList[i].deadline) {
            inspectList[i].deadlineStr = util.formatTime(new Date(inspectList[i].deadline))
          } else {
            inspectList[i].deadlineStr = "无"
          }
          if (!inspectList[i].hiddenDangerLevel) {
            inspectList[i].hiddenDangerLevel = "无"
          }
        }
        that.setData({
          inspectList: res.data.data.dangerInspectListPublicList,
          title: res.data.data.name
        })
        that.countDanger()
      }
    })
  },
  

  //提交当前任务
  doTask(e) {
    var that = this
    Dialog.confirm({
      title: '提示',
      message: '是否提交整改单',
      selector: '#van-dialog-doTask',

    }).then(() => {
      var header;

      header = {
        'Cookie': wx.getStorageSync("sessionid"),//读取cookie
        'content-type': 'application/x-www-form-urlencoded'
      };
      var params = { taskId: that.data.taskId, }

      if (that.data.inspectType == 0) {
        params.type = 0
        params.reform = false
        if (that.data.dangerListCount > 0) {
          params.danger = true
          params.applyUserId = app.globalData.user.userId
          var userIds = new Array()
          userIds.push(app.globalData.user.userId)
          params.userIds = userIds
        } else {
          params.danger = false
        }
      }
      if (that.data.inspectType == 1) {
        params.type = 1
        if (that.data.dangerListCount > 0) {
          params.danger = true
          params.reform = true

        } else {
          params.danger = false
          params.reform = false
        }
      }
      if (that.data.inspectType == 2) {
        params.type = 2
        if (that.data.dangerListCount > 0) {
          params.danger = true
          params.reform = true

        } else {
          params.danger = false
          params.reform = false
        }
      }


      wx.request({
        url: app.globalData.baseUrl + '/safe/dangerFlow/doTask',
        header: header,
        method: "POST",
        data: params,
        success(res) {
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }).catch(() => {
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})